package cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.service.impl;

import cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.RedisUtils;
import cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.entity.Inventory;
import cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.mapper.InventoryMapper;
import cn.caplike.demo.consistence.threadpool.and.blockingqueue.context.service.InventoryService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2020-03-18 16:01
 */
@Service
@Slf4j
public class InventoryServiceImpl implements InventoryService {

    private InventoryMapper inventoryMapper;

    private RedisUtils redisUtils;

    @Override
    public Boolean removeCache(String key) {
        log.info("--- --- --- --- ---> 移除库存 {} 的缓存", key);
        return redisUtils.delete(InventoryService.getKey(key));
    }

    @Override
    public void saveCache(Inventory inventory) {
        final String key = InventoryService.getKey(inventory.getId());
        log.info("--- --- --- --- ---> 保存缓存的数据 {}", key);
        redisUtils.save(key, inventory);
    }

    @Override
    public Inventory getCache(String key) {
        return JSONObject.parseObject(JSONObject.toJSONString(redisUtils.get(InventoryService.getKey(key))), Inventory.class);
    }

    @Override
    public Inventory selectById(String id) {
        return this.inventoryMapper.selectById(id);
    }

    @Override
    public void update(Inventory inventory) {
        log.info("--- --- --- --- ---> 更新库存 {} 的库存记录", inventory.getId());
        inventoryMapper.update(inventory);
    }

    @Override
    public void saveNullForCache(String inventoryKey, long expireTime) {
        final String key = InventoryService.getKey(inventoryKey);
        log.debug("--- --- --- --- ---> 保存空值 {}", key);
        redisUtils.save(key, "", expireTime);
    }

    @Autowired
    public void setInventoryMapper(InventoryMapper inventoryMapper) {
        this.inventoryMapper = inventoryMapper;
    }

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }
}
